const next = require('next')
const express = require('express')
const compression = require('compression')

const port = parseInt(process.env.PORT, 10) || 8868
const dev = process.env.NODE_ENV !== 'production'
const test = process.env.NODE_TEST === 'test'
const app = next({
  dev
})
const handle = app.getRequestHandler()
const devProxy = {
  '/openapi': {
    target: 'http://index-api.meadin.com',
    changeOrigin: true
  }
}

app.prepare()
  .then(() => {
    const server = express()

    if (!dev) {
      server.use(compression()) //gzip
    }

    // Set up the proxy.
    if (dev && devProxy) {
      const proxyMiddleware = require('http-proxy-middleware')
      Object.keys(devProxy).forEach(function (context) {
        server.use(proxyMiddleware(context, devProxy[context]))
      })
    }

    server.get('/index', (req, res) => {
      const actualPage = '/index'
      const queryParams = {id: req.params.id}
      app.render(req, res, actualPage, queryParams)
    })
    server.get('/about', (req, res) => {
      const actualPage = '/about'
      const queryParams = {id: req.params.id}
      app.render(req, res, actualPage, queryParams)
    })
    server.get('*', (req, res) => {
      return handle(req, res)
    })
    server.all('/openapi/*', (req, res) => handle(req, res))

    server.listen(port, (err) => {
      if (err) throw err
      console.log('> Ready on http://localhost:' + port)
    })

  })
  .catch((ex) => {
    console.error(ex.stack)
    process.exit(1)
  })
